package com.sunyard.layoutit.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunyard.layoutit.common.Constant;
import com.sunyard.layoutit.common.DatabaseConfig;
import com.sunyard.layoutit.common.DateUtil;
import com.sunyard.layoutit.pojo.ComponentBoxPojo;
import com.sunyard.layoutit.pojo.RepositoryBoxVo;

public class RepositoryBoxDao {

	private static final Logger logger = LoggerFactory.getLogger(RepositoryBoxDao.class);

	
	public int insert(RepositoryBoxVo vo,DataSource ds) throws SQLException{
		QueryRunner runner=new QueryRunner(ds);
		String sql = "INSERT INTO " + DatabaseConfig.TABLE_PREFIX + "LAYOUTIT_RE_BOX(ID_,REV_,PREVIEW_,VIEW_,GROUP_,CREATE_TIME_,LAST_UPDATE_TIME_) VALUES(?,?,?,?,?,?,?)" ;
		if(null == vo.getID_()){
			String id = String.valueOf(DatabaseConfig.queryNextId("LAYOUTIT_RE_BOX"));
			vo.setID_(id);
		}
		String date = DateUtil.getMDrqzhsti19() ;
		return runner.update(sql, vo.getID_(),1,vo.getPREVIEW_(),vo.getVIEW_(),vo.getGROUP_(),date,date);
	}
	
	public String insert(RepositoryBoxVo vo,Connection conn) throws SQLException{
		QueryRunner runner=new QueryRunner();
		String sql = "INSERT INTO " + DatabaseConfig.TABLE_PREFIX + "LAYOUTIT_RE_BOX(ID_,REV_,PREVIEW_,VIEW_,GROUP_,CREATE_TIME_,LAST_UPDATE_TIME_) VALUES(?,?,?,?,?,?,?)" ;
		if(null == vo.getID_()){
			String id = String.valueOf(DatabaseConfig.queryNextId("LAYOUTIT_RE_BOX"));
			vo.setID_(id);
		}
		String date = DateUtil.getMDrqzhsti19() ;
		runner.update(conn,sql, vo.getID_(),1,vo.getPREVIEW_(),vo.getVIEW_(),vo.getGROUP_(),date,date);
		return vo.getID_();
	}
	
	public int transInsert(String preview , String view , List<String> configurations,String group){
		DataSource dataSource = DatabaseConfig.getDataSource() ;
		Connection conn = null ;
		try {
			conn = dataSource.getConnection() ;
			conn.setAutoCommit(false);
			
			GeneralBytesDao generalBytesDao = DaoFactory.getGeneralBytesDao() ;
			String view_bytes_id = generalBytesDao.insert(view , Constant.BYTEARRAY_NAME_VIEW, conn);
			
			String id = String.valueOf(DatabaseConfig.queryNextId("LAYOUTIT_RE_BOX"));
			RepositoryBoxVo box = new RepositoryBoxVo();
			box.setID_(id);
			box.setREV_(1);
			box.setGROUP_(group);
			box.setPREVIEW_(preview);
			box.setVIEW_(view_bytes_id);
			
			insert(box,conn);
			
			RepositoryBoxConfigDao repositoryBoxConfigDao = DaoFactory.getRepositoryBoxConfigDao() ;
			for(int index = 0;index < configurations.size() ; index++){
				String configuration = configurations.get(index) ;
				String configuration_bytes_id = generalBytesDao.insert(configuration , Constant.BYTEARRAY_NAME_CONFIGURATION, conn);
				repositoryBoxConfigDao.insert("",configuration_bytes_id,index,box.getID_(),conn);
			}
			conn.commit() ;
		} catch (SQLException e) {
			e.printStackTrace();
			if(null != conn){
				try {
					conn.rollback() ;
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
			throw new RuntimeException(e);
		} catch (Exception e) {
			e.printStackTrace();
			if(null != conn){
				try {
					conn.rollback() ;
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
			throw new RuntimeException(e);
		} finally{
			if(null != conn){
				try {
					conn.setAutoCommit(true);
					conn.close() ;
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		return 1 ;
	}
	
	public List<ComponentBoxPojo> queryAllPojo() throws SQLException{
		String sql_box = "SELECT T.ID_,T.REV_,T.PREVIEW_,T.VIEW_,T.CREATE_TIME_,T.LAST_UPDATE_TIME_,T.GROUP_ FROM " 
					+ DatabaseConfig.TABLE_PREFIX + "LAYOUTIT_RE_BOX T ORDER BY T.GROUP_,T.ID_" ;
		
		DataSource dataSource = DatabaseConfig.getDataSource() ;
		QueryRunner runner=new QueryRunner(dataSource);
		return runner.query(sql_box, new ResultSetHandler<List<ComponentBoxPojo>>(){
			public List<ComponentBoxPojo> handle(ResultSet rs) throws SQLException {
				List<ComponentBoxPojo> list = new ArrayList<ComponentBoxPojo>();
				Connection conn = DatabaseConfig.getDataSource().getConnection() ;
				GeneralBytesDao generalBytesDao = DaoFactory.getGeneralBytesDao() ;
				RepositoryBoxConfigDao repositoryBoxConfigDao = DaoFactory.getRepositoryBoxConfigDao() ;
				while(rs.next()){
					ComponentBoxPojo pojo = new ComponentBoxPojo() ;
					String id = rs.getString("ID_") ;
					pojo.setId(id);
					pojo.setDragable(true);
					pojo.setRemovable(true);
					pojo.setPreview(rs.getString("PREVIEW_"));
					pojo.setGroup(rs.getString("GROUP_"));
					String view_html_ref = rs.getString("VIEW_");
					
					String view_html = generalBytesDao.queryText(view_html_ref,conn);
					pojo.setView_html(view_html);
					
					List<String> cfgs = repositoryBoxConfigDao.queryTextByBoxId(id,conn);
					pojo.setConfig_html_list(cfgs);
					list.add(pojo);
				}
				return list;
			}
		});
	}
	
	public Map<String,List<ComponentBoxPojo>> queryAllGroupPojo() throws SQLException{
		List<ComponentBoxPojo> list = queryAllPojo() ;
		if(0 == list.size()){
			logger.warn("Box组件个数为0 ...");
		}
		Map<String,List<ComponentBoxPojo>> map = new HashMap<String,List<ComponentBoxPojo>>() ;
		for(Iterator<ComponentBoxPojo> it = list.iterator();it.hasNext();){
			ComponentBoxPojo pojo = it.next() ;
			String group = pojo.getGroup() ;
			if(!map.containsKey(group)){
				map.put(group, new ArrayList<ComponentBoxPojo>());
			}
			map.get(group).add(pojo);
		}
		return map ;
	}
}
